/**
 */
package com.dingpeikeji.quickdeer.core.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.returnrule.service.TReturnruleService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.DictUtils;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 机构Controller
 * 
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;

	@Autowired
	private TReturnruleService ruleService;

	@ModelAttribute("office")
	public Office get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return officeService.get(id);
		} else {
			return new Office();
		}
	}

	/*
	 * @RequiresPermissions("sys:office:view")
	 * 
	 * @RequestMapping(value = {""}) public String index(Office office, Model
	 * model) { // model.addAttribute("list", officeService.findAll()); return
	 * "modules/sys/officeIndex"; }
	 */

	/*
	 * @RequiresPermissions("sys:office:view")
	 * 
	 * @RequestMapping(value = {"list"}) public String list(Office office, Model
	 * model) { model.addAttribute("list", officeService.findList(office));
	 * return "modules/sys/officeList"; }
	 */

	/**
	 * 旅行商机构
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping("enterpriseList")
	public String enterpriseList(Office office, HttpServletRequest request, HttpServletResponse response, Model model) {
		return list(office, request, response, model, Office.FLAT_TYPE_ENTERPRISE);
	}

	/**
	 * 客运公司
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping("busList")
	public String busList(Office office, HttpServletRequest request, HttpServletResponse response, Model model) {
		return list(office, request, response, model, Office.FLAT_TYPE_BUS);
	}

	/**
	 * 注册企业客户
	 */
	@RequiresPermissions("sys:office:upview")
	@RequestMapping("genList")
	public String genList(Office office, HttpServletRequest request, HttpServletResponse response, Model model) {
		office.setFlatType(Office.FLAT_TYPE_SMALLCO);
		Page<Office> page = officeService.findPage(new Page<Office>(request, response), office);
		model.addAttribute("page", page);
		model.addAttribute("office", office);
		return "modules/sys/genofcList";
	}

	/**
	 * 机构通用列表
	 * 
	 * @param office
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	private String list(Office office, HttpServletRequest request, HttpServletResponse response, Model model,
			String flatType) {
		// office.flatType肯定不为空，根据flatType查找机构列表
		office.setFlatType(flatType);
		Page<Office> page = officeService.findPage(new Page<Office>(request, response), office);
		model.addAttribute("page", page);
		model.addAttribute("office", office);
		return "modules/sys/officeList";
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model, HttpServletRequest request) {
		if (StringUtils.isNotBlank(office.getId())){
			office = officeService.get(office.getId());
		}
		User user = UserUtils.getUser();
		if (office.getParent()==null || office.getParent().getId()==null){
			String node = new String();
			if (office.getFlatType().equals(Office.FLAT_TYPE_BUS)){
				node = Office.OFFICE_NODE_BUS; 
			}else if (office.getFlatType().equals(Office.FLAT_TYPE_ENTERPRISE)) {
				node = Office.OFFICE_NODE_ENTERPRISE;			
			}
				
			// 根据flatType获取上级机构ID
			if (!node.equals("")) {
				Office parent = officeService.findParentByFlatType(node);
				office.setParent(parent);
			}
		}
		// 如果区域为空，默认是当前用户所在部门的区域
		if (office.getArea()==null){
			office.setArea(user.getOffice().getArea());
		}
		//默认值
		if (office.getLocktime() == null)
			office.setLocktime(45);
		
		if (office.getPrtyorder() == null)
			office.setPrtyorder(100);
		
		if (office.getBusinesssuit() == null)
			office.setBusinesssuit("0");
		if (office.getIswifi() == null)
			office.setIswifi("0");
		if (office.getPowersupply() == null)
			office.setPowersupply("0");
		if (office.getTablewater() == null)
			office.setTablewater("0");
		if (office.getPaper() == null)
			office.setPaper("0");
		
		
		model.addAttribute("office", office);
		model.addAttribute("tRuleList", ruleService.findListAll());
		return "modules/sys/officeForm";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "formview")
	public String formview(Office office, Model model, HttpServletRequest request) {
		if (StringUtils.isNotBlank(office.getId())) {
			office = officeService.get(office.getId());
		}

		model.addAttribute("office", office);

		return "modules/sys/officeView";
	}

	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "save")
	public String save(Office office, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/office/";
		}
		if (!beanValidator(model, office)) {
			return form(office, model, request);
		}

		// 机构类型都是部门
		office.setType(Office.TYPE_DEPARTMENT);
		officeService.save(office);

		addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");

		String list = ""; // 平台类型list
		if (office.getFlatType().equals(Office.FLAT_TYPE_BUS)) {
			list = "busList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_ENTERPRISE)) {
			list = "enterpriseList";
		}

		if (office.getFlatType().equals(Office.FLAT_TYPE_SMALLCO)) {
			list = "genList";
		}

		return "redirect:" + adminPath + "/sys/office/" + list;
	}

	@RequiresPermissions("sys:office:upview")
	@RequestMapping(value = "genform")
	public String genform(Office office, Model model, HttpServletRequest request) {
		if (StringUtils.isNotBlank(office.getId())) {
			office = officeService.get(office.getId());
		}
		User user = UserUtils.getUser();
		if (office.getParent() == null || office.getParent().getId() == null) {
			// 根据flatType获取上级机构ID
			Office parent = officeService.findParentByFlatType(Office.OFFICE_NODE_SMALLCOM);
			office.setParent(parent);
		}
		// 如果区域为空，默认是当前用户所在部门的区域
		if (office.getArea() == null) {
			office.setArea(user.getOffice().getArea());
		}

		if (office.getPrtyorder() == null)
			office.setPrtyorder(100);

		if (office.getLocktime() == null)
			office.setLocktime(45);

		model.addAttribute("office", office);

		return "modules/sys/genOfcForm";
	}

	@RequiresPermissions("sys:office:upedit")
	@RequestMapping(value = "goup")
	public String goup(Office office, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, office)) {
			return form(office, model, request);
		}

		// 升级成旅行商
		office.setType(Office.TYPE_DEPARTMENT);
		office.setFlatType(Office.FLAT_TYPE_ENTERPRISE);
		// 父节点切换到旅行商节点
		Office parent = officeService.findParentByFlatType(Office.FLAT_TYPE_ENTERPRISE);
		office.setParent(parent);
		officeService.save(office);

		addMessage(redirectAttributes, office.getName() + "升级成功");

		return "redirect:" + adminPath + "/sys/office/genList";
	}

	// 停用
	@RequiresPermissions("sys:office:upedit")
	@RequestMapping(value = "disableup")
	public String disableup(Office office, RedirectAttributes redirectAttributes) {
		office.setUseable("0");
		officeService.update(office);
		addMessage(redirectAttributes, "停用成功");
		return "redirect:" + adminPath + "/sys/office/genList";
	}

	// 启用
	@RequiresPermissions("sys:office:upedit")
	@RequestMapping(value = "enableup")
	public String enableup(Office office, RedirectAttributes redirectAttributes) {
		office.setUseable("1");
		officeService.update(office);
		addMessage(redirectAttributes, "启用成功");
		return "redirect:" + adminPath + "/sys/office/genList";
	}

	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete")
	public String delete(Office office, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/office/list";
		}
		// if (Office.isRoot(id)){
		// addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
		// }else{
		officeService.delete(office);
		addMessage(redirectAttributes, "停用机构成功");
		// }
		String list = ""; // 平台类型list
		if (office.getFlatType().equals(Office.FLAT_TYPE_BUS)) {
			list = "busList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_ENTERPRISE)) {
			list = "enterpriseList";
		}
		return "redirect:" + adminPath + "/sys/office/" + list + "?id=" + office.getParentId() + "&parentIds="
				+ office.getParentIds();
	}

	// 停用
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "disableOffice")
	public String disableOffice(Office office, RedirectAttributes redirectAttributes) {
		office.setUseable("0");
		officeService.update(office);
		addMessage(redirectAttributes, "停用成功");
		String list = ""; // 平台类型list
		if (office.getFlatType().equals(Office.FLAT_TYPE_BUS)) {
			list = "busList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_ENTERPRISE)) {
			list = "enterpriseList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_SMALLCO)) {
			list = "genList";
		}
		return "redirect:" + adminPath + "/sys/office/" + list;
	}

	// 启用
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "enableOffice")
	public String enableOffice(Office office, RedirectAttributes redirectAttributes) {
		office.setUseable("1");
		officeService.update(office);
		addMessage(redirectAttributes, "启用成功");
		String list = ""; // 平台类型list
		if (office.getFlatType().equals(Office.FLAT_TYPE_BUS)) {
			list = "busList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_ENTERPRISE)) {
			list = "enterpriseList";
		}
		if (office.getFlatType().equals(Office.FLAT_TYPE_SMALLCO)) {
			list = "genList";
		}
		return "redirect:" + adminPath + "/sys/office/" + list;
	}

	/**
	 * 验证公司名是否存在
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "checkOfficeName")
	public String checkOfficeName(String oldOfficeName, String flatType, String name) {
		if (name != null && name.equals(oldOfficeName)) {
			return "true";
		} else if (name != null && officeService.getOfficeByOfficeName(name, flatType) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证组织机构代码是否存在
	 * 
	 * @param oldOrgcode
	 * @param orgcode
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "checkOrgcode")
	public String checkOrgcode(String oldOrgcode, String flatType, String orgcode) {
		if (orgcode != null && orgcode.equals(oldOrgcode)) {
			return "true";
		} else if (orgcode != null && officeService.getOfficeByOrgcode(orgcode, flatType) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证营业执照是否存在
	 * 
	 * @param oldLicenseno
	 * @param licenseno
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "checkLicenseno")
	public String checkLicenseno(String oldLicenseno, String flatType, String licenseno) {
		if (licenseno != null && licenseno.equals(oldLicenseno)) {
			return "true";
		} else if (licenseno != null && officeService.getOfficeByLicenseno(licenseno, flatType) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证税务登记证是否存在
	 * 
	 * @param oldTaxregno
	 * @param taxregno
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "checkTaxregno")
	public String checkTaxregno(String oldTaxregno, String flatType, String taxregno) {
		if (taxregno != null && taxregno.equals(oldTaxregno)) {
			return "true";
		} else if (taxregno != null && officeService.getOfficeByTaxregno(taxregno, flatType) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 获取机构JSON数据。
	 * 
	 * @param extId
	 *            排除的ID
	 * @param type
	 *            类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade
	 *            显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
			@RequestParam(required = false) String type, @RequestParam(required = false) Long grade,
			@RequestParam(required = false) String flatType, @RequestParam(required = false) Boolean isAll,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(isAll);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId)
					|| (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& (flatType == null || (flatType != null && flatType.equals(e.getFlatType())))
					&& Global.YES.equals(e.getUseable())) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

	@ResponseBody
	@RequestMapping(value = "treeDataNoright")
	public List<Map<String, Object>> treeDataNoright(@RequestParam(required = false) String extId,
			@RequestParam(required = false) String type, @RequestParam(required = false) Long grade,
			@RequestParam(required = false) String flatType, @RequestParam(required = false) Boolean isAll,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findListUnselect(flatType);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId)
					|| (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& (flatType == null || (flatType != null && flatType.equals(e.getFlatType())))
					&& Global.YES.equals(e.getUseable())) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
}
